﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Mockery.Core
{
    /// <summary>
    /// Holds the test context that needs to be cleaned up at a later point in time
    /// </summary>
    public class DisposableContextState : IDisposableContextState
    {
        private List<IDisposable> _disposableList = new List<IDisposable>();

        /// <summary>
        /// Adds any provided non-null disposable instance to the list of items to be disposed
        /// </summary>
        /// <param name="disposableInstance">an instance deriving from IDisposable</param>
        public void Add( IDisposable disposableInstance )
        {
            if( disposableInstance != null)
               _disposableList.Add(disposableInstance);
        }

        /// <summary>
        /// The count of all items waiting to be disposed
        /// </summary>
        public int Count { get { return _disposableList.Count(); } }

        /// <summary>
        /// Performs a Dispose call on each instance in the collected state
        /// </summary>
        public void Dispose()
        {
            foreach (var disposableInstance in _disposableList)
                disposableInstance.Dispose();

            _disposableList.Clear();
        }
    }
}
